import { ArgumentsHost, Catch, ExceptionFilter, HttpException } from '@nestjs/common';
import { Request, Response } from 'express';

// 异常过滤器  处理返回异常的格式

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    const status = exception.getStatus();

    response
      .status(status)
      .json({
        statusCode: status,
        code: -1,
        timestamp: new Date().toISOString(),
        path: request.url,
        otherMsg: exception.getResponse(),  // 接受单独的自定义的异常处理信息
        msg: '绑定的异常过滤器'
      });
  }
}
